package client;

import java.io.*;
import java.net.*;

public class ClientNetService
{
	private Socket socket;
	private PrintWriter out;
	private BufferedReader in;
	
	
	public ClientNetService(String login, String host, int port)
		throws UnknownHostException, IOException, UsernameTakenException
	{
		socket = new Socket();
		socket.connect(new InetSocketAddress(host, port), 1000);
		
		out = new PrintWriter(socket.getOutputStream(), true);
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
		System.out.println("Sending to srv: " + ("H " + login));
		out.println("H " + login);
		String resp = in.readLine();
		System.out.println("Serv resp: " + resp);
		
		if(resp == null)
		{
			close();
			throw new IOException();
		}
		
		if(resp.equals("UT"))
		{
			close();
			throw new UsernameTakenException();
		}
	}
	
	public void printLine(String line)
	{
		  out.println(line);
	}
	
	public String readLine() throws IOException
	{
		return in.readLine();
	}
	
	public void close()
	{
		try
		{
			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {}
	}
}
